<template>
  <!-- 添加一个外层 view 标签作为根标签 -->
  <view>
    <view
      v-for="(toast, index) in toasts"
      :key="index"
      :class="[
        'custom-toast',
        toast.show ? 'custom-toast-show' : 'custom-toast-hide',
        getPositionClass(toast.position),
      ]"
    >
      {{ toast.message }}
    </view>
  </view>
</template>

<script>
export default {
  name: "Toast",
  data() {
    return {
      toasts: [],
    };
  },
  methods: {
    showToast(options) {
      const { msg = "", duration = 2000, position = "bottom" } = options;
      if (typeof duration !== "number" || duration < 0) {
        console.error("Invalid duration provided. Using default value.");
        duration = 2000;
      }

      // 新toast出现时让旧的toast进入关闭状态
      this.toasts.forEach((toast) => {
        if (toast.show) {
          this.closeToast(toast);
        }
      });

      const newToast = {
        message: msg,
        show: true,
        position,
        timer: null,
      };
      this.toasts.push(newToast);

      newToast.timer = setTimeout(() => {
        this.closeToast(newToast);
      }, duration);
    },
    closeToast(toast) {
      // 确保 DOM 更新后再触发过渡动画
      this.$nextTick(() => {
        if (this.$el) {
          const index = this.toasts.indexOf(toast);
          const el = this.$el.querySelectorAll(".custom-toast")[index];
          if (el) {
            el.classList.remove("custom-toast-show");
            el.classList.add("custom-toast-hide");
          }
        }
        toast.show = false;
        setTimeout(() => {
          const index = this.toasts.indexOf(toast);
          if (index !== -1) {
            this.toasts.splice(index, 1);
          }
        }, 500);
      });
    },
    getPositionClass(position) {
      switch (position) {
        case "top":
          return "custom-toast-top";
        case "center":
          return "custom-toast-center";
        case "bottom":
        default:
          return "custom-toast-bottom";
      }
    },
  },
  mounted() {
    this.$nextTick(() => {
      // 监听 toasts 数组变化，确保动画能正常触发
      this.$watch(
        "toasts",
        (newToasts, oldToasts) => {
          if (this.$el) {
            newToasts.forEach((toast, index) => {
              const el = this.$el.querySelectorAll(".custom-toast")[index];
              if (el) {
                if (toast.show) {
                  el.classList.remove("custom-toast-hide");
                  el.classList.add("custom-toast-show");
                } else {
                  el.classList.remove("custom-toast-show");
                  el.classList.add("custom-toast-hide");
                }
              }
            });
          }
        },
        { deep: true }
      );
    });
  },
  // 微信小程序可能需要在组件销毁时做一些清理工作
  beforeDestroy() {
    this.toasts.forEach((toast) => {
      if (toast.timer) {
        clearTimeout(toast.timer);
      }
    });
  },
};
</script>

<style scoped lang="scss">
$transition-duration: 0.3s;

// 定义向上移动的关键帧动画(关闭动画)
@keyframes slideUpFadeOut {
  from {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
  }
  to {
    opacity: 0;
    transform: translateX(-50%) translateY(-100px);
  }
}
// 定义向上移动的关键帧动画（开始动画）
@keyframes slideUpFadein {
  from {
    opacity: 0;
    transform: translateX(-50%) translateY(-10rpx) scale(0.1);
  }
  to {
    opacity: 1;
    transform: translateX(-50%) translateY(0) scale(1);
  }
}

.custom-toast {
  position: fixed;
  left: 50%;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
  opacity: 0;
  transform: translateX(-50%);
  z-index: 9999;
}

.custom-toast-show {
//   opacity: 1;
//   transform: translateX(-50%);
  animation: slideUpFadein 0.3s ease-out forwards;
}

.custom-toast-hide {
  animation: slideUpFadeOut $transition-duration;
}

.custom-toast-top {
  top: 50px;
}

.custom-toast-center {
  top: 50%;
  transform: translate(-50%, -50%);
}

.custom-toast-bottom {
  bottom: 50px;
}
</style>    